package com.lanzchina.lanclass.service;

import com.lanzchina.lanclass.domain.Result;
import com.lanzchina.lanclass.domain.User;
import com.lanzchina.lanclass.repository.UserRepository;
import com.lanzchina.lanclass.utils.Md5Util;
import com.lanzchina.lanclass.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private OpenIdService openIdService;

    /**
     * 根据code调用wxApi获取openId，用openId来查找用户，以校验该openId是否绑定用户账号
     * @param code 用于获取openId
     * @param validateCode 验证码
     * @return 没有绑定用户账号，或 用户所有信息
     */
    public Result findByCode(String code, String validateCode) {
        String myValidateCode = Md5Util.validateCode("code", code);
        if (!myValidateCode.equals(validateCode)) {
            return ResultUtil.error(0, "验证失败");
        }

        String openId = getOpenId(code);
        User user = userRepository.findByOpenId(openId);
        if (user == null) {
            return ResultUtil.error(0, "该openId未绑定用户账号");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("userInfo", formatUserInfo(user));
        data.put("schoolInfo", schoolService.formatSchoolInfo(user.getSchool()));
        return ResultUtil.success(data);
    }

    public String getOpenId(String code) {
        // TODO: 使用feign调用微信api获取openId；
        String openId = openIdService.getOpenId(code);
        return code;
    }

    Map<String, Object> formatUserInfo(User user) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", user.getUserId());
        userInfo.put("username", user.getUsername());
        userInfo.put("userType", user.getUserType());
        return userInfo;
    }
}
